package com.bbcare.followup.plat.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientQueueService;
import com.bbcare.followup.plat.store.ibatis.IPatientOperationRecordDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;

/*
 * @name:         患者队列信息服务类实现
 * @createTime:   2017.4.11
 * @description:  患者相关操作等
 * @modify:
 * 
 */
@Service
public class PatientQueueService implements IPatientQueueService {
    private final Log logger = LogFactory.getLog(PatientQueueService.class);

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;
    
    @Autowired
    private IPatientInfoHisService patientInfoHisService;
    
    @Autowired
    private IPatientOperationRecordDAO patientOperationRecordDao;

	@Override
	@Transactional
	public int queuePatientModify(Map<String, Object> paramMap)
			throws Exception {
		logger.debug("in queuePatientModify ....");
		// pt_queuescheme_info更新及历史轨迹变化记录
		String queueSchemeId = (String)paramMap.get("queueSchemeId");
        Map<String, Object> queueMap = new HashMap<String, Object>();
        queueMap.put("id", queueSchemeId);
//        queueMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        //判断当前患者队列关系是否存在
        List<PatientQueueScheme> ptQList = patientQueueSchemeDao.selectPatientByCondition(queueMap);
        
        PatientQueueScheme ptQ = null;
        if(CollectionUtils.isEmpty(ptQList)){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "患者不在当前队列中");
        }else{
        	ptQ = ptQList.get(0);
        	if(Constants.PATIENT_QUEUESCHEME_USER_STATUS_DELETE.equals(ptQ.getUserStatus())){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "患者不在当前队列中");
        	}else if(!Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND.equals(ptQ.getUserStatus())
        			&&Constants.PATIENT_QUEUE_OPCODE_RECOVERY.equals(paramMap.get("opCode"))){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_SUSPEND, "当前患者状态不是暂停状态，不需要恢复");
        	}else if(!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(ptQ.getUserStatus())
        			&&Constants.PATIENT_QUEUE_OPCODE_SUSPEND.equals(paramMap.get("opCode"))){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL, "当前患者状态非正常状态，不能暂停");
        	}else if(!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(ptQ.getUserStatus())
        			&&!Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND.equals(ptQ.getUserStatus())){
        		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL, "当前患者状态存在问题，不能进行暂停|恢复操作");
        	}
        }
        
        if(Constants.PATIENT_QUEUE_OPCODE_SUSPEND.equals(paramMap.get("opCode"))){
        	queueMap.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
        }else {//传入其他值 默认为恢复
        	queueMap.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        }
        
        String sysDate = DateUtil.getSysDateA();
        queueMap.put("updateTime",sysDate);
        queueMap.put("updateAuthor", paramMap.get("authorId"));
        //记录轨迹
        queueMap.put("updateAccept", paramMap.get("updateAccept"));
        queueMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
		int i = patientQueueSchemeDao.updatePtQueueSchemeRecord(queueMap);
		patientQueueSchemeDao.insertPatientQueueSchemeHis(queueMap); //记录队列历史
		
		//记录操作流水
		Map<String, Object> paramRecord = new HashMap<String, Object>();
        paramRecord.put("userName", paramMap.get("userName"));
        paramRecord.put("userId", paramMap.get("userId"));
        paramRecord.put("queueId", ptQ.getQueueId());
        paramRecord.put("authorId", paramMap.get("authorId"));
        paramRecord.put("opTime", paramMap.get("updateTime"));
        paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_11);
        paramRecord.put("opUsertype", Constants.OPCODE_TYPE_DOCTOR);
        paramRecord.put("authorName", paramMap.get("authorName"));
        if(Constants.PATIENT_QUEUE_OPCODE_SUSPEND.equals(paramMap.get("opCode"))){
        	paramRecord.put("opCode",Constants.OP_CODE_1005);
        }else {//传入其他值 默认为恢复
        	paramRecord.put("opCode",Constants.OP_CODE_1006);
        }
        paramRecord.put("updateAccept", paramMap.get("updateAccept"));
        paramRecord.put("tenantId", paramMap.get("tenantId"));
        paramRecord.put("remark", paramMap.get("opNote"));
        paramRecord.put("opType", Constants.OP_TYPE_QUEUE);
        Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
        patientOperationRecordDao.saveOperationRecord(outRecord);
		//操作记录  通过切面
		return i;
	}

	@Override
	public List<Map<String, Object>> patientAuditRecordList(
			Map<String, Object> paramMap) throws Exception {
		logger.info("in patientAuditRecordList");
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		Object userNameObject = paramMap.get("userName");
		Object userName = (userNameObject!=null &&!StringUtils.isEmpty(userNameObject)) ? "%"+userNameObject.toString()+"%" : userNameObject ; 
		
		paramMap.put("userName",userName);
		paramMap.put("page", rows*(page-1));
		paramMap.put("rows", rows);
		
		List<Map<String, Object>> list = patientQueueSchemeDao.selectQueueAuditTask(paramMap);
		logger.info("out patientAuditRecordList");
		return list;
	}

	@Override
	@Transactional
	public void updateAuditTask(Map<String, Object> paramMap) throws Exception {
		//更新用户在队列中状态
		String status= (String)paramMap.get("status");
		
		//判断当前患者队列关系是否存在
		Map<String, Object> temp = new HashMap<String,Object>();
		temp.put("queueId",paramMap.get("queueId"));
		temp.put("userId",paramMap.get("userId"));
		temp.put("status",Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT);
        List<PatientQueueScheme> ptQList = patientQueueSchemeDao.selectPatientByCondition(temp);
        PatientQueueScheme ptQ = null;
        if(CollectionUtils.isEmpty(ptQList)){
        	throw new AppException("10202004", "患者不在当前队列中");
        }else{
        	ptQ = ptQList.get(0);
        }
        temp = new HashMap<String,Object>();
        if(Constants.PATIENT_AUDIT_PASS.equals(status)){
        	temp.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        }else{
        	temp.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOTPASS);
        }
        
        temp.put("id", ptQ.getId());
        String sysDate = DateUtil.getSysDateA();
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);
        temp.put("updateTime",sysDate);
        temp.put("updateAuthor", paramMap.get("authorId"));
        //记录轨迹
        temp.put("updateAccept",updateAccept);
        temp.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        
        patientQueueSchemeDao.updatePtQueueSchemeRecord(temp);
		patientQueueSchemeDao.insertPatientQueueSchemeHis(temp);
		
		//更新审核表
		Map<String, Object> updateAudit = new HashMap<String,Object>();
		updateAudit.putAll(paramMap);
		patientQueueSchemeDao.updateAuditTask(paramMap);
	
	}

	@Override
	public int patientAuditRecordCount(Map<String, Object> paramMap)
			throws Exception {
		return patientQueueSchemeDao.selectQueueAuditTaskCount(paramMap);
	}

	@Override
	public List<Map<String, Object>> getQueueStopPatientList(
			Map<String, Object> paramMap) throws Exception {
		logger.info("in getQueueStopPatientList");
        int page = (paramMap.get("page") != null && !StringUtils.isEmpty(paramMap.get("page").toString()))
                ? Integer.parseInt(paramMap.get("page").toString()) : 1;
        int rows = (paramMap.get("rows") != null && !StringUtils.isEmpty(paramMap.get("rows").toString()))
                ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
        Object userNameObject = paramMap.get("userName");
        Object userName = (userNameObject != null && !StringUtils.isEmpty(userNameObject))
                ? "%" + userNameObject.toString() + "%" : userNameObject;

        paramMap.put("userName", userName);
        paramMap.put("page", rows * (page - 1));
        paramMap.put("rows", rows);
//      paramMap.put("normalStatus","1");
        paramMap.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
        List<Map<String, Object>> list = patientQueueSchemeDao.selectQueueStopPatientlist(paramMap);
		return list;
	}

	@Override
	public int getQueueStopPatientCount(Map<String, Object> paramMap)
			throws Exception {
		return patientQueueSchemeDao.selectQueueStopPatientCount(paramMap);
	}
	
	

}
